<script setup lang="ts">
/**
 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
 */
defineOptions({
  name: "Robot",
  inheritAttrs: false,
});
import { uploadFileApi } from "@/api/library/index";
import {
  ElMessage,
  ElMessageBox,
  ElUpload,
  UploadRawFile,
  UploadRequestOptions,
} from "element-plus";
import dayjs from "dayjs";
import {
  addRobot,
  RobotList,
  FormRobot,
  Robotunbind,
  updateRobot,
  LibraryOptions,
} from "@/api/robot";
import useUserStore from "@/store/modules/user";
let useStore = useUserStore();
import { onMounted, ref, reactive, watch, nextTick } from "vue";
import { Picture as IconPicture } from "@element-plus/icons-vue";
const userFormRef = ref(); // 用户表单
let LibOptions = ref([] as any);
const loading = ref(false);
const ids = ref([]);
const total = ref(0);
let dialog = reactive({
  visible: false,
  title: "",
});

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
});
const RobotListT = ref([{}] as any);

let formData = ref({
  status: 1,
  mapInfo: [
    {
      id: 1,
      x: 0,
      y: 0,
    },
  ],
  mapUrl: "",
  filePath: "",
} as any);

/**
 * 查询
 */
function getRobotList() {
  loading.value = true;
  RobotList(queryParams.value)
    .then((res: any) => {
      if (res.code == 200) {
        const updatedRobotList = res.data.records.map((record: any) => {
          const timestamp = record.createTime; // 假设时间戳单位为秒
          const date = dayjs(timestamp);
          const formattedDate = date.format("YYYY/MM/DD HH:mm:ss"); // 使用 dayjs.format 方法转换为指定的日期时间格式

          record.createTime = formattedDate;

          return record;
        });
        RobotListT.value = updatedRobotList;
        total.value = res.data.total;
        // console.log(res.data, "res.data");
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

const rules = reactive({
  libraryId: [
    { required: true, message: "请选择图书馆", trigger: ["blur", "change"] },
  ],
  robotCode: [
    { required: true, message: "机器人编号不能为空", trigger: "blur" },
  ],
  robotName: [
    { required: true, message: "机器人名称不能为空", trigger: "blur" },
  ],
  robotStatus: [{ required: true, message: "请选择状态", trigger: "change" }],
  mapUrl: [
    {
      required: true,
      message: "请选择地图",
      trigger: "change",
    },
  ],
});

/**
 * 修改用户状态
 */
// function handleStatusChange(row: { [key: string]: any }) {
//   const text = row.status === 1 ? "启用" : "停用";
//   ElMessageBox.confirm("确认要" + text + row.username + "用户吗?", "警告", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消",
//     type: "warning",
//   })
//     .then(() => {
//       return editUserStatus({ id: row.id, status: row.status });
//     })
//     .then(() => {
//       ElMessage.success(text + "成功");
//     })
//     .catch(() => {
//       row.status = row.status === 1 ? 0 : 1;
//     });
// }

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 解绑
 */
const Unbind = (row: any) => {
  ElMessageBox.confirm("此操作将解绑该机器人?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async function () {
      await Robotunbind(row);
      ElMessage.success("该机器人解绑成功");
      getRobotList();
    })
    .catch(() => {});
};
/**
 * 打开弹窗
 *
 * @param userId 用户ID
 */

async function openDialog(userId?: number) {
  dialog.visible = true;
  if (userId) {
    const ress = await LibraryOptions(useStore.encryptedData);
    LibOptions.value = ress.data;
    const res = await FormRobot(userId);
    formData.value = res.data;
    srcList.value.splice(0, srcList.value.length);
    srcList.value.push(formData.value.mapUrl);
    //console.log(res, "FormRobot");
    dialog.title = "修改机器人呢";
  } else {
    if ((dialog.title = "新增机器人")) {
      const res = await LibraryOptions(useStore.encryptedData);
      LibOptions.value = res.data;
      libraryIdFormRef.value.clearValidate();

      // console.log(LibOptions.value, "LibOptions");
      formData.value = {};
      resetUploadFiles(); // 清空上传文件列表
    }
  }
  dialog.visible = true;
}

/**
 * 关闭用户弹窗
 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}
const libraryIdFormRef = ref();
/**
 * 重置表单
 */
function resetForm() {
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  formData.value = {};
  libraryIdFormRef.value.clearValidate();
  resetUploadFiles(); // 清空上传文件列表
}

/**
 * 表单提交
 */
const handleSubmit = () => {
  userFormRef.value.validate((valid: any) => {
    if (valid) {
      if (isUploading.value) {
        ElMessage.warning("文件上传中，请稍后再试");
        return;
      }
      const userId = formData.value.id;
      loading.value = true;
      if (userId) {
        // console.log(formData.value, "编辑");
        updateRobot(formData.value)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            getRobotList();
          })
          .finally(() => (loading.value = false));
      } else {
        //  console.log("新增");
        addRobot(formData.value)
          .then((res) => {
            if (res.code == 200) {
              dialog.visible = false;
              ElMessage.success("新增成功");
              getRobotList();
              closeDialog();
            } else {
              ElMessage.error(res.msg);
            }
          })
          .finally(() => (loading.value = false));
      }
    }
  });
};
/**
 * 删除用户
 */
// function handleDelete(id?: number) {
//   const userIds = [id || ids.value].join(",");
//   if (!userIds) {
//     ElMessage.warning("请勾选删除项");
//     return;
//   }
//   ElMessageBox.confirm("确认删除用户?", "警告", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消",
//     type: "warning",
//   }).then(function () {
//     // console.log(Number(userIds), userIds);

//     delUser(id).then((res) => {
//       if (res.code == 200) {
//         ElMessage.success("删除成功");
//         getRobotList();
//       }
//     });
//   });
// }

onMounted(() => {
  getRobotList(); // 初始化用户列表数据
});
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val;
  queryParams.value.pageNum = 1;

  getRobotList();
};
const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  getRobotList();
  window.scrollTo({ top: 0, behavior: "smooth" }); // 立即回到顶部，并使用平滑滚动效果
};
const getStatus = (status: number) => {
  const STATUSES = [
    { id: -1, name: "离线" },
    { id: 0, name: "在线" },
    { id: 1, name: "工作中" },
    { id: 2, name: "充电中" },
    { id: 255, name: "故障" },
  ];
  const matched = STATUSES.find((item) => item.id === status);
  return matched ? matched.name : "";
};
// 枚举类型，定义状态码和对应的类型
enum RobotStatusType {
  SUCCESS = "success",
  WARNING = "warning",
  DANGER = "danger",
}

// 函数，根据状态码返回el-tag的类型
const statusType: (status: number) => string = (status) => {
  switch (status) {
    case 0:
      return RobotStatusType.SUCCESS;
    case -1:
      return RobotStatusType.WARNING;
    case 255:
      return RobotStatusType.DANGER;
    default:
      return "success"; // 默认类型
  }
};
const indexMethod = (index: any) => {
  // 1、index:代表当前行数据的下标
  // 2、下标+1:  分页不要纠结：这块不是业务，完全是数学问题！
  return (
    index + 1 + (queryParams.value.pageNum - 1) * queryParams.value.pageSize
  );
};
/**
 * 限制用户上传文件的格式和大小
 */
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
const ALLOWED_TYPES = [
  "image/bmp", // BMP
  "image/jpeg", // JPEG
  "image/png", // PNG
  "image/gif", // GIF
  "image/tiff", // TIFF
  "image/svg+xml", // SVG
  "image/webp", // WebP
];
const fileToUpload = ref<File | null>(null); // 用于存储待上传的文件
function handleBeforeUpload(file: UploadRawFile) {
  const isAllowedType = ALLOWED_TYPES.includes(file.type);
  if (!isAllowedType) {
    ElMessage.warning(
      "只允许上传 BMP、JPEG、PNG、GIF、TIFF、SVG、WebP 格式的图片"
    );
    return false;
  }
  if (file.size > MAX_FILE_SIZE) {
    ElMessage.warning("上传图片不能大于10M");
    return false;
  }
  fileToUpload.value = file; // 存储文件
  return true;
}

/**
 * 自定义图片上传
 *
 * @param options
 */

const srcList = ref<string[]>([]);

const uploadRef = ref<InstanceType<typeof ElUpload>>();
const isUploading = ref(false); // 用于跟踪上传状态
async function uploadFile(options: UploadRequestOptions): Promise<void> {
  //console.log("上传文件触发", options.file); // 调试信息
  try {
    isUploading.value = true; // 开始上传
    const { data: fileInfo } = await uploadFileApi(options.file);
    formData.value.mapUrl = fileInfo.fileUrl;
    formData.value.filePath = fileInfo.filePath;
    srcList.value = [fileInfo.fileUrl];
    //console.log(fileInfo.fileUrl, fileInfo.filePath);
  } catch (error) {
    //console.error("上传失败:", error);
    ElMessage.error("上传失败，请重试");
  } finally {
    isUploading.value = false; // 上传完成
  }
}
// 监听 dialogVisible 变化
watch(dialog, (newVal) => {
  if (newVal) {
    resetUploadFiles();
  }
});

// 重置上传文件
function resetUploadFiles() {
  nextTick(() => {
    if (uploadRef.value) {
      uploadRef.value.clearFiles(); // 清空文件列表
    }
  });
}
// --------------------
const mapInfo = ref();
const useMarker = () => {
  const markers = ref();

  function moveMarker(id: number, newX: number, newY: number) {
    const marker = markers.value.find((m) => m.id === id);
    if (marker) {
      const containerRect = document
        .querySelector(".marker-container")
        .getBoundingClientRect();
      const markerSize = 20; // Assuming marker size as 20px, adjust if necessary
      const maxX = containerRect.width - markerSize;
      const maxY = containerRect.height - markerSize;

      marker.x = Math.max(0, Math.min(newX, maxX));
      marker.y = Math.max(0, Math.min(newY, maxY));
      // 发送更新后的点位数据给后端
      mapInfo.value = markers.value.map((m) => ({
        id: m.id,
        x: m.x,
        y: m.y,
      }));
    }
  }

  return {
    markers,
    moveMarker,
  };
};
const { markers, moveMarker } = useMarker();
// -----------------------------------------------------------------------------
const dialogVisible = ref(false);
const bgdimg = ref();
const PositionID = ref();
const currentLocation = ref(); //当前坐标亮点
const trueLO = ref(false);
const Position = async (row: any) => {
  trueLO.value = false;
  markers.value = [];
  bgdimg.value = "";
  dialogVisible.value = true;
  PositionID.value = row.id;
  const res = await FormRobot(row.id);

  // setInterval(async () => {
  //   const res = await FormRobot(PositionID.value);
  //   currentLocation.value = res.data.currentLocation;
  // }, 10000);
  if (res.code == 200) {
    markers.value = JSON.parse(res.data.mapInfo);
    bgdimg.value = res.data.mapUrl;
    currentLocation.value = res.data.currentLocation;
    //currentLocation.value = res.data.currentLocation; //.replace(/^0+/, "")

    // 监听 res.data.currentLocation 的变化并更新 currentLocation.value
    // watch(
    //   () => res.data.currentLocation,
    //   (newVal) => {
    //     currentLocation.value = newVal;
    //     console.log("currentLocation updated:", currentLocation.value);
    //   },
    //   { immediate: true }
    // );

    console
      .log
      // res.data.currentLocation,
      // markers.value,
      // "位置弹框",
      //currentLocation.value
      ();
  }
};

const Close = () => {
  dialogVisible.value = false;
};

function startDrag(id: number, event: { clientX: any; clientY: any }) {
  const marker = markers.value.find((m) => m.id === id);
  if (!marker) return;

  const startX = event.clientX;
  const startY = event.clientY;
  const initialX = marker.x;
  const initialY = marker.y;

  function move(event: { clientX: number; clientY: number }) {
    const deltaX = event.clientX - startX;
    const deltaY = event.clientY - startY;
    moveMarker(id, initialX + deltaX, initialY + deltaY);
  }

  function stop() {
    window.removeEventListener("mousemove", move);
    window.removeEventListener("mouseup", stop);
  }

  window.addEventListener("mousemove", move);
  window.addEventListener("mouseup", stop);
}
const Submit = () => {
  updateRobot({ id: PositionID.value, mapInfo: mapInfo.value })
    .then(() => {
      ElMessage.success("保存成功");
      // console.log("点位保存成功");
      Close();
    })
    .catch((error) => {
      console.error("保存点位时出错:", error);
    });
};
const newMarker = {
  id: 1,
  x: 0,
  y: 0,
};
const addNewMarker = () => {
  // 假设这里给新点分配一个唯一的 ID
  newMarker.id = markers.value.length + 1;
  markers.value.push({ ...newMarker });
};

// function handleDelete(id) {
//   const index = markers.value.findIndex((m) => m.id === id);
//   if (index !== -1) {
//     markers.value.splice(index, 1); // 从 markers 数组中删除对应的 marker
//     // 在这里可以添加删除后的其他逻辑，比如保存更新等
//     updateRobot({ id: PositionID.value, mapInfo: markers.value })
//       .then(() => {
//         ElMessage.success("删除成功");
//         console.log("点位删除成功");
//       })
//       .catch((error) => {
//         console.error("删除点位时出错:", error);
//       });
//   }
// }
function handleModify(id) {
  const markerIndex = markers.value.findIndex((m) => m.id === id);
  if (markerIndex !== -1) {
    const marker = markers.value[markerIndex];
    const action = prompt("请选择操作:\n1. 编辑\n2. 删除");

    if (action === "1") {
      // 编辑操作
      const newName = prompt("修改位置坐标:", marker.id);
      if (newName !== null) {
        marker.id = newName;
        mapInfo.value = markers.value;
        // updateRobot({ id: PositionID.value, mapInfo: markers.value })
        //   .then(() => {
        //     ElMessage.success("修改成功");
        //     console.log("点位修改成功");
        //   })
        //   .catch((error) => {
        //     console.error("修改点位时出错:", error);
        //   });
      }
    } else if (action === "2") {
      // 删除操作
      markers.value.splice(markerIndex, 1);
      mapInfo.value = markers.value;
      // updateRobot({ id: PositionID.value, mapInfo: markers.value })
      //   .then(() => {
      //     ElMessage.success("删除成功");
      //     console.log("点位删除成功");
      //   })
      //   .catch((error) => {
      //     console.error("删除点位时出错:", error);
      //     // 如果删除失败，可能需要将 marker 重新插入到 markers 中
      //     markers.value.splice(markerIndex, 0, marker);
      //   });
    } else {
      // 用户取消操作或输入无效选项
    }
  }
}
</script>

<template>
  <div class="app-container">
    <el-row>
      <el-col>
        <el-card shadow="never">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button type="success" @click="openDialog()"
                  ><el-icon><Plus /></el-icon>新增</el-button
                >
                <!-- <el-button
                  type="danger"
                  :disabled="ids.length === 0"
                  @click="handleDelete()"
                  ><i-ep-delete />删除</el-button -->
              </div>
            </div>
          </template>

          <el-table
            v-loading="loading"
            :data="RobotListT"
            :border="true"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="index"
              width="80"
              label="序号"
              :align="'center'"
              :index="indexMethod"
            />
            <el-table-column
              label="机器人名称"
              align="center"
              prop="robotName"
            />
            <el-table-column
              label="机器人编号"
              align="center"
              prop="robotCode"
            />
            <el-table-column
              label="机器人状态"
              prop="agvStatus"
              :align="'center'"
            >
              <template #default="{ row }">
                <el-tag :type="statusType(row.robotStatus)">
                  {{ getStatus(row.robotStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="电量" align="center" prop="currentPower" />
            <el-table-column label="主板" align="center" prop="mainBoard" />
            <el-table-column label="MAC地址" align="center" prop="mac" />
            <el-table-column label="机器人类型" align="center" prop="type" />

            <el-table-column
              label="自检报告"
              align="center"
              prop="selfInspectionReport"
              show-overflow-tooltip
            />

            <!-- <el-table-column label="主板" align="center" prop="mainBoard" />
            <el-table-column label="MAC地址" align="center" prop="mac" />
            <el-table-column label="机器人类型" align="center" prop="type" />
            <el-table-column
              label="充电次数"
              align="center"
              prop="chargingCount"
            />
            <el-table-column
              label="雷达状态"
              align="center"
              prop="radarStatus"
            />
            <el-table-column label="运行时长" align="center" prop="runTime" />
            <el-table-column label="超声" align="center" prop="ultrasound" />
            <el-table-column label="电机轮毂" align="center" prop="hubMotor" /> -->
            <!-- <el-table-column
              label="自检报告"
              align="center"
              prop="selfInspectionReport"
            /> -->
            <!-- <el-table-column label="状态" align="center" prop="status">
              <template #default="scope">
                <el-switch
                  v-if="scope.row.status !== undefined"
                  v-model="scope.row.status"
                  :inactive-value="0"
                  :active-value="1"
                  @change="handleStatusChange(scope.row)"
                />
              </template>
            </el-table-column> -->
            <el-table-column
              label="创建时间"
              align="center"
              prop="createTime"
            />
            <el-table-column
              label="操作"
              fixed="right"
              width="220"
              align="center"
            >
              <template #default="{ row }">
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="Unbind(row.id)"
                  >解绑</el-button
                >

                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="openDialog(row.id)"
                  icon="Edit"
                  >编辑</el-button
                >
                <el-button
                  v-if="row.mapUrl"
                  type="primary"
                  link
                  style="font-size: 20px"
                  size="small"
                  @click="Position(row)"
                  icon="Location"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            style="margin-top: 15px"
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 30, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      append-to-body
      @close="closeDialog"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="图书馆" prop="libraryId" ref="libraryIdFormRef">
          <el-select v-model="formData.libraryId" placeholder="请选择图书馆">
            <el-option
              v-for="item in LibOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="机器人编号" prop="robotCode">
          <el-input
            v-model="formData.robotCode"
            placeholder="请输入机器人编号"
            maxlength="20"
          />
        </el-form-item>

        <el-form-item label="机器人名称" prop="robotName">
          <el-input
            v-model="formData.robotName"
            placeholder="请输入机器人名称"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item label="机器人状态" prop="robotStatus">
          <el-radio-group v-model="formData.robotStatus">
            <el-radio :value="0">在线</el-radio>
            <el-radio :value="-1">离线</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="地图" prop="mapUrl" ref="uploadref">
          <el-image
            style="width: 100px; height: 100px"
            :src="formData.mapUrl"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            fit="cover"
            :preview-src-list="srcList"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><icon-picture /></el-icon>
              </div>
            </template>
          </el-image>

          <el-upload
            :show-file-list="false"
            ref="uploadRef"
            class="upload-demo"
            action="#"
            :before-upload="handleBeforeUpload"
            :http-request="uploadFile"
          >
            <el-button type="primary" link>上传文件</el-button>
          </el-upload>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="handleSubmit"
            :disabled="isUploading"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogVisible"
      :before-close="Close"
      style="background-color: transparent; width: 680px"
    >
      <div
        class="marker-container"
        :style="{ backgroundImage: 'url(' + bgdimg + ')' }"
      >
        <div
          v-for="marker in markers"
          :key="marker.id"
          class="marker"
          :style="{
            left: marker.x + 'px',
            top: marker.y + 'px',
            backgroundColor: marker.id == currentLocation ? 'green' : '',
          }"
          @mousedown="startDrag(marker.id, $event)"
          @dblclick="handleModify(marker.id)"
        >
          <span
            style="
              display: flex;
              font-size: 10px;
              justify-content: center;
              align-items: center;
            "
            >{{ marker.id }}</span
          >
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="addNewMarker">新增点位</el-button>
          <el-button type="primary" @click="Submit">保 存</el-button>
          <el-button @click="Close">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}
.image-slot .el-icon {
  font-size: 20px;
}
.marker-container {
  position: relative;
  width: 650px;
  height: 650px;
  background-color: transparent;
  background-size: 650px 650px; /* 设置宽度为100像素，高度为50像素 */
}

.marker {
  position: absolute;
  width: 15px;
  height: 15px;
  background-color: red; /* Adjust marker style */
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: bottom;
  color: white;
  font-weight: bold;
}
</style>
